<?php

class cms_event_model extends CI_Model {

    protected $_instance = array(
        'table' => 'cms_event',
        'primaryKey' => 'id',
    );
    protected $_parent = null;
    public $_data = null;

    public function get_events($reload = false) {
        $CI = & get_instance();
        $list_event = null;
        if ($reload) {
            $query = $this->db->get($this->_instance['table']);
            foreach ($query->result() as $row) {
                $list_event[] = $row;
            }
            $query->free_result();
            $CI->st_registry->setKey('cms/event/collection', $list_event, GLOBAL_CACHE_DURATION);
        } else {
            $list_event = $CI->st_registry->getKey('cms/event/collection');
            if (empty($list_event)) {
                return $this->get_events(true);
            }
        }
        return $list_event;
    }

    public function get_list()
    {
        $query = $this->db->query('SELECT id, title, is_active FROM cms_event ORDER BY path ASC');
        $list_event = array();
        foreach ($query->result() as $row) {
            $list_event[] = $row;
        }
        $query->free_result();
        return $list_event;
    }

    public function get_collection($start, $limit, $conds = null, $orders = null) {
        $query = 'SELECT id, title, is_active, description FROM cms_event';
        if (is_array($conds)) {
            $conds = implode(' AND ', $conds);
        }
        if (!empty($conds)) {
            $query .= ' WHERE ' . $conds;
        }
        if (!empty($orders)) {
            $query .= ' ORDER BY ' . $orders;
        }
        if (!empty($limit)) {
            $query .= ' LIMIT ' . $start . ', ' . $limit;
        }
        $query = $this->db->query($query);
        $list_event = array();
        foreach ($query->result() as $row) {
            $list_event[] = $row;
        }
        $query->free_result();
        return $list_event;
    }

    public function get_by_ids($ids) {
        if (empty($ids)) {
            return null;
        }
        $query = 'SELECT id, title, alias FROM ' . $this->_instance['table'] . ' WHERE id IN ('.$ids.')';
        $rs = $this->db->query($query);
        $collection = $rs->result();
        $rs->free_result();
        return $collection;
    }

    public function add_event($data) {
        $data = $this->auto_render($data);
        $CI = & get_instance();
        $data['user_id'] = $CI->session->userdata('admin_id');
        if (empty($data['error'])) {
            $this->db->insert($this->_instance['table'], $data);
            // Update Cache
            $CI->st_registry->deleteKey('cms/event/collection');
        } else {
            throw new Exception($data['error']);
            return false;
        }
        return $this;
    }
    
    public function update_event($id, $data) {
        $data = $this->auto_render($data);
        $CI = & get_instance();
        $data['user_id'] = $CI->session->userdata('admin_id');
        if (empty($data['error'])) {
            $this->db->where('id', $id);
            $this->db->update($this->_instance['table'], $data);
            // Update Cache
            $CI->st_registry->deleteKey('cms/event/collection');
            $CI->st_registry->deleteKey('cms/event_by_id/' . $id);
            if (!empty($data['alias'])) {
                $CI->st_registry->deleteKey('cms/event_by_id/' . $data['alias']);
            }
        } else {
            throw new Exception($data['error']);
            return false;
        }
        return $this;
    }
    
    public function load_by_id($id, $reload = false) {
        $this->_data = null;
        $CI = & get_instance();
        if ($reload) {
            $query = $this->db->get_where($this->_instance['table'], array('id' => $id), 1, 0);
            $this->_data = $query->row();
            $query->free_result();
            $CI->st_registry->setKey('cms/event_by_id/' . $id, $this->_data, CACHE_TIMEOUT);
        } else {
            $this->_data = $CI->st_registry->getKey('cms/event_by_id/' . $id);
            if (empty($this->_data)) {
                $this->_data = $this->load_by_id($id, true);
            }
        }
        if (!empty($this->_data->article_ids) && is_string($this->_data->article_ids)) {
            $this->_data->article_ids = explode(',', $this->_data->article_ids);
        }
        if (empty($this->_data->article_ids)) {
            $this->_data->article_ids = array();
        }
        return $this->_data;
    }
    
    public function delete_event($id) {
        $file = $this->get_file($id);
        @unlink($file);
        $this->db->delete($this->_instance['table'], array('id' => $id));
        // Update Cache
        $CI = & get_instance();
        $CI->st_registry->deleteKey('cms/event/collection');
        $CI->st_registry->deleteKey('cms/event_by_id/' . $id);
        return $this;
    }

    private function auto_render($data) {
        $data['updated_at'] = time();
        $alias = renderToAlias($data['title']);
        if (empty($data['alias'])) {
            $data['alias'] = $alias;
        }
        if (empty($data['meta_keywords'])) {
            $data['meta_keywords'] = $alias;
        }
        if (empty($data['meta_title'])) {
            $data['meta_title'] = $data['title'];
        }
        if (empty($data['meta_description'])) {
            $data['meta_description'] = $data['title'];
        }
        if (!empty($data['article_ids']) && is_array($data['article_ids'])) {
            $data['article_ids'] = implode(',', $data['article_ids']);
        }
        return $data;
    }

    public static function get_url($event = null) {
        if (empty($event)) {
            return route_model::get_route('article/article/home');
        }
        if (is_string($event)) {
            return BASE_URL . 'tin-tuc/' . $event . '.html';
        }
        if (is_object($event) && isset($event->alias) && isset($event->id)) {
            return BASE_URL . 'tin-tuc/' . $event->alias . '-c' . $event->id . '.html';
        }
        if (is_array($event) && isset($event['alias']) && isset($event['id'])) {
            return BASE_URL . 'tin-tuc/' . $event['alias'] . '-c' . $event['id'] . '.html';
        }
        return null;
    }

    public function get_article_collection($evt_id, $start = 0, $limit = 15) {
        $sql = 'SELECT id, title, alias, description, image, tags, publish_day FROM cms_article WHERE CONCAT(",", event_ids, ",") LIKE "%,' . $evt_id . ',%" AND publish = 1 ORDER BY publish_day DESC LIMIT '.$start.', ' . $limit;
        $query = $sql;
        $rs = $this->db->query($query);
        $collection = $rs->result();
        $rs->free_result();
        return $collection;
    }

    public function get_file($id) {
        $query = 'SELECT file FROM '.$this->_instance['table'].' WHERE id = ' . $id . ' ORDER BY id DESC LIMIT 0, 1';
        $rs = $this->db->query($query);
        $row = $rs->row();
        $rs->free_result();
        return $row->file;
    }
}

?>